package com.tanhua.app.service;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.easemob.im.server.api.message.MessageApi;
import com.tanhua.app.exception.BusinessException;
import com.tanhua.app.exception.ErrorResult;
import com.tanhua.app.interceptor.UserHolder;
import com.tanhua.commons.utils.Constants;
import com.tanhua.config.template.HuanXinTemplate;
import com.tanhua.dubbo.api.FriendApi;
import com.tanhua.dubbo.api.UserApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.model.pojo.User;
import com.tanhua.model.pojo.UserInfo;
import com.tanhua.model.vo.ContactVo;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.UserInfoVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class MessagesService {

    @DubboReference
    private UserApi userApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    @DubboReference
    private FriendApi friendApi;

    //根据环信id查询用户详细信息
    public UserInfoVo findUserInfoByHuanXing(String huanxinId) {
        //根据huanxingId查询userId
        User user = userApi.findByHuanXinId(huanxinId);
        //根据userId查询用户详细信息
        UserInfo userInfo = userInfoApi.findById(user.getId());
        //将结果封装到vo中
        UserInfoVo vo = new UserInfoVo();
        BeanUtils.copyProperties(userInfo,vo);
        if (userInfo.getAge() != null){
            vo.setAge(userInfo.getAge().toString());
        }
        return vo;
    }

    //添加联系人
    public void contacts(Long friendId) {
        //1.将好友信息注册到环信
        Boolean addContact = huanXinTemplate.addContact(Constants.HX_USER_PREFIX + UserHolder.getUserId(), Constants.HX_USER_PREFIX + friendId);
        //2.判断是否注册成功 如果注册成功 将好友信息保存到monggoDB
        if (!addContact){
            throw new BusinessException(ErrorResult.friendError());
        }
        friendApi.save(UserHolder.getUserId(),friendId);
    }

    //获取联系人列表 并根据关键字查询
    public PageResult<ContactVo> contactsPage(Integer page, Integer pagesize, String keyword) {
        //根据登录用户id查询出所有的好友 id集合
        List<Long> ids = friendApi.findByUserId(UserHolder.getUserId());
        if (CollUtil.isEmpty(ids)){
            return new PageResult(page,pagesize,0,null);
        }
        //根据ids查询好友信息集合
        Page<UserInfo> pages = userInfoApi.findInfoPage(ids,page,pagesize,keyword);
        //封装到vo中
        List<ContactVo> vos = new ArrayList<>();
        for (UserInfo userInfo : pages.getRecords()) {
            ContactVo vo = ContactVo.init(userInfo);
            vos.add(vo);
        }

        return new PageResult(page,pagesize,0,vos);
    }
}
